using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace OpenComposite.Mapper
{
	public partial class formXmlViewer : Form
	{
		public formXmlViewer()
		{
			InitializeComponent();

			xmlEditor.SetHighlighting("XML");
		}

		public XmlDocument XmlDocument
		{
			get { return _xmldoc; }
			set
			{
				_xmldoc = value;
				if ( _xmldoc != null ) {
					XmlWriterSettings settings = new XmlWriterSettings();
					settings.Indent = true;
					settings.IndentChars = "\t";
					using ( StringWriter sw = new StringWriter() )
					using ( XmlWriter xw = XmlWriter.Create(sw, settings) ) {
						_xmldoc.WriteTo(xw);
						xw.Flush();
						xmlEditor.Text = sw.ToString();
					}
					treeXML.Nodes.Clear();
					if ( _xmldoc != null && _xmldoc.DocumentElement != null ) {
						treeXML.BeginUpdate();
						treeXML.Nodes.Add(fillTreeRecursive(_xmldoc.DocumentElement));
						treeXML.ExpandAll();
						treeXML.EndUpdate();
					}
				}
			}
		}
		private TreeNode fillTreeRecursive(XmlNode xnCurrent)
		{
			TreeNode tn = null;
			if ( xnCurrent is XmlText ) {
				tn = new TreeNode(( (XmlText)xnCurrent ).Data);
			} else {
				tn = new TreeNode("<" + xnCurrent.Name);
				if ( xnCurrent.Attributes != null ) {
					foreach ( XmlAttribute xa in xnCurrent.Attributes ) {
						tn.Text += string.Format(" {0}=\"{1}\"", xa.Name, xa.Value);
					}
				}
				tn.Text += ">";
				foreach ( XmlNode xn in xnCurrent.ChildNodes ) {
					tn.Nodes.Add(fillTreeRecursive(xn));
				}
			}
			return tn;
		}
		private XmlDocument _xmldoc = null;

		private void formXmlViewer_FormClosing(object sender, FormClosingEventArgs e)
		{
			//SemanticParserService.Stop();
		}
	}
}